<template>
  <div class="send-panel">
    <Avatar
      :avatar="
        !homeStore.userInfo || Object.keys(homeStore.userInfo).length == 0
          ? ''
          : homeStore.userInfo.avatar
      "
    ></Avatar>

    <div class="input-panel">
      <template v-if="showSend">
        <el-form :model="formData" :rules="rules" ref="formDataRef" @submit.prevent>
          <el-form-item label="" prop="" class="input-area">
            <el-input
              type="textarea"
              :rows="1"
              clearable
              :placeholder="formData.nickName ? '@' + formData.nickName : ''"
              v-model="formData.content"
              show-word-limit
              :maxlength="500"
              :autosize="{ minRows: 1, maxRows: 5 }"
              resize="none"
            ></el-input>
            <div class="comment-image" v-if="formData.imgPath">
              <Cover fit="cover" :source="formData.imgPath"></Cover>
              <span class="del iconfont icon-close" @click="delImage"></span>
            </div>
          </el-form-item>
        </el-form>
        <div class="op-panel">
          <div class="op-btns">
            <el-popover
              ref="elPopoverRef"
              width="500"
              :show-arrow="false"
              :offset="5"
              trigger="click"
              placement="bottom-start"
              :teleported="false"
            >
              <template #reference>
                <div class="iconfont icon-emoji"></div>
              </template>
              <template #default>
                <el-tabs v-model="activeEmoji" @click.stop>
                  <el-tab-pane
                    v-for="emoji in emojiList"
                    :key="emoji.name"
                    :label="emoji.name"
                    :name="emoji.name"
                  >
                    <div class="emoji-list">
                      <div
                        v-for="(item, index) in emoji.emojiList"
                        :key="index"
                        class="emoji-item"
                        @click="sendEmoji(item)"
                      >
                        {{ item }}
                      </div>
                    </div>
                  </el-tab-pane>
                </el-tabs>
              </template>
            </el-popover>
            <el-upload
              ref="uploadRef"
              :multiple="false"
              :show-file-list="false"
              :http-request="selectFile"
              :accept="imageAccept"
            >
              <div class="iconfont icon-image"></div>
            </el-upload>
          </div>
          <div class="send-btn">
            <el-button type="primary" @mousedown="submitComment">发布</el-button>
          </div>
        </div>
      </template>
      <div class="no-send" v-else>UP已关闭评论区</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useHomeStore } from '@/stores/home'
import { onBeforeUnmount, onMounted, onUnmounted, ref, withDefaults } from 'vue'
import emojiList from '@/utils/Emoji'
import { mitter } from '@/eventbus/eventBus'
import message from '@/utils/message'
import { useRoute } from 'vue-router'
import { postCommentHttpRequest, uploadImageHttpRequest } from '@/services/api/video'
import type { UploadRequestHandler, UploadRequestOptions } from 'element-plus'

const props = withDefaults(
  defineProps<{
    sendType?: number
    showSend?: boolean
  }>(),
  {
    showSend: true
  }
)

const route = useRoute()
const homeStore = useHomeStore()

//表单数据
const formData = ref({
  content: '',
  imgPath: '',
  nickName: ''
})
const formDataRef = ref()

const rules = {
  title: [{ required: true, message: '请输入内容' }]
}

const delImage = () => {
  formData.value.imgPath = ''
}

//插入表情
const elPopoverRef = ref()
const activeEmoji = ref('笑脸')
//选择emoji表情
const sendEmoji = (item: any) => {
  formData.value.content = formData.value.content ? formData.value.content + item : item
  elPopoverRef.value.hide()
}
//发布评论
const submitComment = async (e: any) => {
  e.preventDefault()
  if (!homeStore.userInfo || Object.keys(homeStore.userInfo).length == 0) {
    homeStore.setLogin(true)
    return
  }
  //判断是在评论区的评论的还是直接评论
  const params =
    props.sendType == 0
      ? { content: formData.value.content, imgPath: formData.value.imgPath }
      : Object.assign({}, formData.value)
  if (!params.content) {
    message.warning('请输入评论')
    return
  }
  const requestParams = {
    ...params,
    videoId: route.params.videoId as string
  }
  if (requestParams.imgPath) {
    //上传封面 上传完成之后获取返回的路径赋值给表单数据
    const imgPath = await uploadImageHttpRequest({
      file: requestParams.imgPath as unknown as File,
      createIsThumbnail: true
    })
    requestParams.imgPath = imgPath.data
  }
  //发布评论
  const res = await postCommentHttpRequest({
    ...requestParams
  })
  formDataRef.value.resetFields()
  //清空数据
  Object.keys(formData.value).forEach((key) => {
    formData.value[key as keyof typeof formData.value] = ''
  })
  message.success('发布成功')
  mitter.emit('postCommentSuccess', res.data)
}

//插入图片
const selectFile: UploadRequestHandler = (file: UploadRequestOptions) => {
  console.log(file, '图片')
  formData.value.imgPath = file.file as unknown as string
  return Promise.resolve() // 返回一个 resolved 的 Promise
}
//上传文件能接受的后缀
const imageAccept = ref('.jpg,.png,.gif,.bmp,.webp')

onMounted(() => {
  mitter.on('initCommentData', (data: any) => {
    console.log(data, 'initCommentData')

    if (props.sendType != 0) {
      formData.value = Object.assign({}, data)
    }
  })
})

onBeforeUnmount(() => {
  mitter.off('initCommentData')
})
</script>

<style lang="less" scoped>
.send-panel {
  margin-top: 20px;
  display: flex;
  .input-panel {
    flex: 1;
    margin-left: 15px;
    :deep(.el-form-item) {
      margin-bottom: 0;
    }

    .no-send {
      background-color: #ebebeb;
      text-align: center;
      padding: 15px;
      border-radius: 5px;
      color: var(--text3);
    }
    .input-area {
      border: 1px solid #ddd;
      border-radius: 5px;
      padding: 8px;
      :deep(.el-textarea__inner) {
        box-shadow: none;
        padding: 0px;
      }
      .comment-image {
        margin-top: 5px;
        width: 72px;
        height: 72px;
        display: flex;
        align-items: center;
        position: relative;
        .del {
          position: absolute;
          top: 0;
          right: 0;
          background: #0003;
          width: 20px;
          height: 20px;
          color: #fff;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 0 5px 0 5px;
          cursor: pointer;
        }
      }
    }
    .op-panel {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 5px;
      .op-btns {
        display: flex;
        align-items: center;
        .iconfont {
          cursor: pointer;
          border: 1px solid #ddd;
          padding: 3px 8px;
          margin-right: 5px;
          border-radius: 5px;
        }
      }
    }
  }
}

.emoji-list {
  .emoji-item {
    float: left;
    font-size: 23px;
    padding: 2px;
    text-align: center;
    border-radius: 3px;
    margin-left: 10px;
    margin-top: 5px;
    cursor: pointer;
    &:hover {
      background-color: #ddd;
    }
  }
}
</style>
